package cc.shacocloud.redis.study.bloom_filter;

import cc.shacocloud.redis.study.util.env.YamlConfigurer;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class RedissonExample {

    public static void main(String[] args) {
        YamlConfigurer configurer = YamlConfigurer.getDefault();

        Config config = new Config();
        config.useSingleServer().setAddress
                ( // 节点地址
                        configurer.resolveRequiredPlaceholders("redis://${redis.host}:${redis.port}")
                );

        RedissonClient redisson = Redisson.create(config);
        RBloomFilter<String> bloomFilter = redisson.getBloomFilter("shacocloud:bf");

        int size = 100000;
        // 初始化布隆过滤器
        bloomFilter.tryInit(size, 0.0001);

        for (int i = 0; i < size; i++) {
            bloomFilter.add(String.valueOf(i));
        }

        log.info("数据初始化成功！");

        // 计算误伤
        int start = size + 1;
        int end = size + 200000;
        List<Integer> list = new ArrayList<>();
        for (int i = start; i < end; i++) {
            if (bloomFilter.contains(String.valueOf(i))) {
                list.add(i);
            }
        }

        log.info("误伤数：" + list.size());

        redisson.shutdown();
    }
}
